<?php

class blogs extends Module {
	
	public function __construct () {
		parent::__construct (__CLASS__);
	}
	
	public function __default () {
		throw new NotFound;
	}
	
	public function list_blogs () {
		$oTypeBlog = TypesController::getInstance()->getTypeByName ('blog');
		
		$sel = new Selection;
		$sel->addType ($oTypeBlog);
		$sel->setOrder ('title');
		
		$aObjects = ObjectsController::getInstance()->getObjectsList ($sel->getList ());
		
		$response = new ModuleResponse;
		$response->setTemplate ('blogs/blogsList');
		
		if (getRequest ('deleted','bool')) {
			$response->addObject (new SystemMessage (lang('admin_blog_deleted',__CLASS__)));
		}
		
		foreach ($aObjects as $object) {
			$response->addObject ($object);
		}
		
		return $response;
	}
	
	public function delete_blog () {
		$oTypeBlog = TypesController::getInstance()->getTypeByName ('blog');
		
		$blogId = getRequest ('param0','int');
		
		if (!$oBlog = ObjectsController::getInstance()->getObject ($oTypeBlog, $blogId)) {
			throw new NotFound;
		}
		
		$oBlog->delete ();
		redirect (HTTP_HOST . '/admin/blogs/list_blogs?deleted');
	}
	
	public function posts () {
		$typesController = TypesController::getInstance ();		
		
		$sel = new Selection;
		
		$selTypes = new Selection;
		$selTypes->addType (TypesController::getInstance()->getTypeByName ('post_type'));
		$selTypes->addSelectedProperty ('type_id');
		
		$res = $selTypes->getList ();
		foreach ($res as $item) {
			$sel->addType ($typesController->getTypeById ($item['type_id']));
		}
		
		$sel->addFilter ('draft', 0);
		$sel->setOrder ('pubdate', false);
		
		$currentPage = getRequest ('page', 'int');
		if ($currentPage > 0) {
			$currentPage--;
		}
		
		$sel->addLimit ($currentPage*20, 20);
		
		$aObjects = ObjectsController::getInstance()->getObjectsList ($sel->getList ());
		
		$response = new ModuleResponse;
		$response->setTemplate ('blogs/posts');
		
		if (getRequest ('deleted','bool')) {
			$response->addObject (new SystemMessage (lang('admin_post_deleted',__CLASS__)));
		}
		
		foreach ($aObjects as $object) {
			$response->addObject ($object);
		}
		
		$response->addObject (new Array2XML ('pages', array (
			'onpage' => 20,
			'total' => $sel->getTotalCount (),
			'page' => ++$currentPage
		)));
		
		return $response;
	}
	
	public function delete_post () {
		$this->expectSecureGET ();
		
		$typeId = getRequest ('param0','int');
		$objectId = getRequest ('param1','int');
		
		if (!$oType = TypesController::getInstance()->getTypeById ($typeId)) {
			throw new NotFound;
		}
		
		if (!$object = ObjectsController::getInstance()->getObject ($oType, $objectId)) {
			throw new NotFound;
		}
		
		$object->delete ();
		
		redirect (HTTP_HOST . '/admin/blogs/posts?deleted');
	}
}